package com.server;

import com.Config;
import com.entity.Request;
import com.entity.Response;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Server {

    public String account;
    public String iP;
    ServerSocket server = null;
    Socket socket = null;

    public Server(String account, String iP) {
        this.account = account;
        this.iP = iP;
        try {
            this.server = new ServerSocket(6666);
            System.out.println("创建房间：房间创建成功");
            socket = server.accept();

            //数据库相关
            Connection conn = DriverManager.getConnection(Config.JDBCURL, "zxeao", "123456");
            String sql = String.format("SELECT account FROM `account` WHERE (ip='%s') AND (account!='%s') ",iP,account);
            PreparedStatement statement  = conn.prepareStatement(sql);
            ResultSet res = statement.executeQuery();

            if (res.next()) {
                System.out.println("客户端连接-------账户"+res.getString(1)+"连接成功");
            }

            while (true){
                InputStream is=socket.getInputStream();
                ObjectInputStream ois=new ObjectInputStream(is);
                Request request=(Request)ois.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(Response response){
        try {
            OutputStream os=socket.getOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(os);
            oos.writeObject(response);
            System.out.println("发出数据");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
